package org.blueoxygen.kukuruyuk.action.masterreceipe;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import org.apache.commons.beanutils.PropertyUtils;
import org.blueoxygen.cimande.LogInformation;
import org.blueoxygen.kukuruyuk.entity.MasterReceipe;
import org.blueoxygen.kukuruyuk.entity.PurchaseOrder;
public class SaveMasterReceipe extends MasterReceipeForm {
     public String execute(){
          if(getMasterreceipe().getRealizeDate() == null ||
                  "".equalsIgnoreCase(getMasterreceipe().getRealizeDate())){
              addActionError("Realize Date is not null");
          }
          if(getMasterreceipe().getVahicleNumber() == null ||
                  "".equalsIgnoreCase(getMasterreceipe().getVahicleNumber())){
              addActionError("Vahicle Number is not null");
          }
          if(hasErrors()){
              return INPUT;
          }
          LogInformation log;
          if(getMasterreceipe().getId() == null ||
                  "".equalsIgnoreCase(getMasterreceipe().getId())){
              log = new LogInformation();
              log.setCreateBy(sessionCredentials.getCurrentUser().getId());
              log.setCreateDate(new Timestamp(System.currentTimeMillis()));
              getMasterreceipe().setId(null);
          } else {
              MasterReceipe temp = getMasterreceipe();
              setMasterreceipe((MasterReceipe) manager.getById(MasterReceipe.class, getMasterreceipe().getId()));
              log = getMasterreceipe().getLogInformation();
              try {
                  PropertyUtils.copyProperties(getMasterreceipe(), temp);
              } catch (IllegalAccessException e) {
               e.printStackTrace();
           } catch (InvocationTargetException e) {
               e.printStackTrace();
           } catch (NoSuchMethodException e) {
               e.printStackTrace();
           }
       }
          if(hasErrors()){
              setPos(manager.findAllSorted(PurchaseOrder.class, "name"));
              return INPUT;
          }
          if(getPo().getId() != null &&
  !"".equalsIgnoreCase(getPo().getId())){
              setPo((PurchaseOrder) manager.getById(PurchaseOrder.class,
                      getPo().getId()));
          } else {
              setPo(null);
          }
          getMasterreceipe().setPurchaseOrder(getPo());
          getMasterreceipe().setLogInformation(log);
          manager.save(getMasterreceipe());

       log.setLastUpdateBy(sessionCredentials.getCurrentUser().getId());
       log.setLastUpdateDate(new Timestamp(System.currentTimeMillis()));
       log.setActiveFlag(1);
       getMasterreceipe().setLogInformation(log);
       manager.save(getMasterreceipe());
       return SUCCESS;
   }
}
